package me.zhengjie.modules.weixin.processor;

import me.zhengjie.config.exception.WeChatException;
import me.zhengjie.modules.weixin.dto.WeChatAccount;
import me.zhengjie.modules.weixin.message.AbstractMessage;
import me.zhengjie.modules.weixin.message.AnalyzerReplyMessage;
import me.zhengjie.modules.weixin.utils.ClazzUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Constructor;

/**
 * 实际处理消息类
 *
 */
@Component
public class ProcessorFactory {


    public AbstractMessage process(WeChatAccount account, AnalyzerReplyMessage reply) throws Exception {

        if (null == reply || StringUtils.isBlank(reply.getModule())) {
            throw new WeChatException("Not Found The Module: " + (null != reply ? reply.getModule() : ""));
        }

        Class<?> clazz = ClazzUtil.INSTANCE.getProcessor(reply.getModule());
        if (null == clazz) {
            throw new WeChatException("Class Not Found For The Module: " + reply.getModule());
        }

        Constructor<?> constructor = clazz.getConstructor(WeChatAccount.class, AnalyzerReplyMessage.class);
        AbstractProcessor processor = (AbstractProcessor) constructor.newInstance(account, reply);

        return processor.process();
    }
}
